package com.itheima.service.impl;

import com.itheima.dao.AccountDao;
import com.itheima.service.AccountService;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.sql.DataSource;

/**
 * @author cp
 * @className AccountServiceImpl
 * @description TODO
 * @create 2020/12/8 19:17
 **/
public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;
    private DataSource dataSource;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public void transfer(String outName, String inName, Double money) {
        // 创建事务管理器
        // 为事务管理器设置与数据层相同的数据源
        PlatformTransactionManager ptm = new DataSourceTransactionManager(dataSource);

        // 创建事务定义对象
        TransactionDefinition td = new DefaultTransactionDefinition();

        // 创建事务状态对象，用于控制事务执行
        TransactionStatus ts = ptm.getTransaction(td);

        accountDao.inMoney(outName,money);
//        int a = 1/0;          // 模拟业务层事务过程中出现错误
        accountDao.outMoney(inName,money);

        // 提交事务
        ptm.commit(ts);
    }
}
